/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.edu.curso.java.dao;

import br.edu.curso.java.VO.DisciplinaVO;
import java.util.ArrayList;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

/**
 *
 * @author rafael
 */
public class DisciplinaDAO  {
    
	private Session session;

	public void incluir(DisciplinaVO p) {
		try {
			session = BaseHibernate.getSession();
			session.beginTransaction();
			session.save(p);
			session.getTransaction().commit();
		} catch (Exception e) {
			session.getTransaction().rollback();
			e.printStackTrace();
		}finally{
			session.close();
		}
	}

	public void alterar(DisciplinaVO p) {
		try {
			session = BaseHibernate.getSession();
			session.beginTransaction();
			session.update(p);
			session.getTransaction().commit();
		} catch (Exception e) {
			session.getTransaction().rollback();
		}finally{
			session.close();
		}
	}
	
	public void excluir(DisciplinaVO p) {
		try {
			session = BaseHibernate.getSession();
			session.beginTransaction();
			session.delete(p);
			session.getTransaction().commit();
		} catch (Exception e) {
			session.getTransaction().rollback();
		}finally{
			session.close();
		}
	}

	public DisciplinaVO retornar(int codigo) {
		DisciplinaVO retorno = new DisciplinaVO();
		try {
			session = BaseHibernate.getSession();
			session.beginTransaction();
			retorno = (DisciplinaVO) session.get(DisciplinaVO.class, codigo);
			session.getTransaction().commit();
		} catch (Exception e) {
			session.getTransaction().rollback();
		}finally{
			session.close();
		}
		return retorno;
	}

	@SuppressWarnings("unchecked")
	public List<DisciplinaVO> listar() {
		List<DisciplinaVO> lista = new ArrayList<DisciplinaVO>();
		try {
			session = BaseHibernate.getSession();
			session.beginTransaction();
			lista = (List<DisciplinaVO>) session.createCriteria(DisciplinaVO.class).list();
			session.getTransaction().commit();
		} catch (Exception e) {			
			session.getTransaction().rollback();
		}finally{
			session.close();
		}
		return lista;
	}

	@SuppressWarnings("unchecked")
	public List<DisciplinaVO> listar(DisciplinaVO disciplina) {
		Criteria c = session.createCriteria(DisciplinaVO.class);
		if (disciplina.getDescricao().length() > 0) {
			c.add(Restrictions.like("descricao", disciplina.getDescricao() + "%"));
		}
		c.addOrder(Order.asc("descricao"));
		return (List<DisciplinaVO>) c.list();
	}

}
